package com.gzist.elderlyserviceplatform.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzist.elderlyserviceplatform.entity.dto.ListQueryPageDTO;
import com.gzist.elderlyserviceplatform.entity.po.Comment;
import com.gzist.elderlyserviceplatform.entity.vo.ClientCommentVo;
import com.gzist.elderlyserviceplatform.entity.vo.CommentPageVO;
import com.gzist.elderlyserviceplatform.mapper.CommentMapper;
import com.gzist.elderlyserviceplatform.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 评论信息表 服务实现类
 */
@Service
@RequiredArgsConstructor
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    private final CommentMapper commentMapper;

    @Override
    public Page<CommentPageVO> queryPage(ListQueryPageDTO listQueryPageDTO) {
        Page<CommentPageVO> page = new Page<>(listQueryPageDTO.getPageNum(), listQueryPageDTO.getPageSize());
        return commentMapper.queryPage(page, listQueryPageDTO);
    }

    @Override
    public Integer getCommentsByRootId(String rootId) {
        // 根据Comment的rootId进行查询数据条数
        LambdaQueryWrapper<Comment> wrapper = Wrappers.lambdaQuery();
        if (StrUtil.isBlank(rootId)) {
            return 0;
        }
        wrapper.eq(Comment::getRootId, rootId);
        return Convert.toInt(this.count(wrapper));
    }

    @Override
    public List<ClientCommentVo> list(String id) {

        //1.先查根据活动id查出所有的评论
        if (StrUtil.isBlank(id)) {
            return null;
        }
        //一级评论全部查出来
        List<ClientCommentVo> comments = commentMapper.list(id);
        //有评论的话，遍历找到全部的子评论
        if (comments.size() > 0) {
            for (ClientCommentVo clientCommentVo : comments) {
                List<ClientCommentVo> childCommentList = commentMapper.list1(id, clientCommentVo.getId());
                clientCommentVo.setChildCommentList(childCommentList);
            }
        }
        return comments;
    }

    //  添加评论
    @Override
    public void addComment(Comment comment) {
        comment.setUserId(StpUtil.getLoginIdAsString());
        this.save(comment);
    }

    @Override
    public void addReplyComment(Comment comment) {
        comment.setUserId(StpUtil.getLoginIdAsString());
        this.save(comment);
    }


}
